var tool = require('../../tool');
var models = require('../../models');
var methods = {
    'get':function (req, res, render) {
        req.session._loginReferer = req.get('referer') || '';
        render({});
    },
    'post':function (req, res) {
        var body = req.body;
        var userModel = models['user'];
        var password = tool.md5(body['password']);
        console.log('check user info');
        userModel.findOne({
            mail:body['mail']
        }, 'password', function (err, doc) {
            if (err) {
                console.log(err);
                return;
            }
            console.log(doc.password);
            if (doc && password == doc.password) {
                res.cookie('user', tool.encrypt(doc['_id'] + '', 'itravel'), {
                    path:'/',
                    maxAge:60 * 60 * 24 * 30
                });
                //res.cookie('user','');
            }
            res.redirect(req.session._loginReferer);
            //render(doc);
        });
    }
};
module.exports = function (req, res) {
    if (req.session.user && req.session.user.username) {
        var referer = req.get('referer') || '';
        res.redirect(referer);
    }
    var methodName = req.method.toLowerCase();
    var render = function (data) {
        res.render('user/login', {
            'title':'Show This',
            'data':data
        }, 0);
    };
    methods[methodName](req, res, render);
};